package com.example.service.impl;

import com.example.entity.Order;
import com.example.entity.PageBean;
import com.example.mapper.OrderMapper;
import com.example.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public Order findByOrderid(String order_id) {
        Order order = orderMapper.findByOrderid(order_id);
        return order;
    }
    @Override
    public Integer insertOrder(Order order) throws ParseException {
        String randomHexString = generateHexValue(32);
        order.setOrderNum(randomHexString);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = dateFormat.parse(dateFormat.format(new Date()));
        order.setOrderTimestart(currentTime);
        orderMapper.insert(order);
        int newOrderId = order.getOrderId();
        return newOrderId;
    }

    @Override
    public void updata(Order order) {
        orderMapper.updata(order);
    }
    @Override
    public void delete(String order_id) {
        orderMapper.delete(order_id);
    }

    @Override
    public Order findByOrderTableid(String tableId) {
        return orderMapper.findByOrdertableId(tableId);
    }

    @Override
    public PageBean orderList(Integer page, Integer pageSize, String query) {
        int start=(page-1)*pageSize;
        List<Order> orderList= orderMapper.orderList(start,pageSize,query);
        long total=orderMapper.orderTotal(start,pageSize,query);
        return new PageBean(total,orderList);
    }

    public String generateHexValue(int length) {
            SecureRandom random = new SecureRandom();
            byte[] bytes = new byte[length / 2];
            random.nextBytes(bytes);
            return String.format("%0" + length + "x", new java.math.BigInteger(1, bytes));
    }

    @Override
    public List<Order> orderListById(String customerId) {
        return orderMapper.orderListById(customerId);
    }

    @Override
    public List<Order> orderListByIdNo(String customerId) {
        return orderMapper.orderListByIdNo(customerId);
    }

    @Override
    public List<Order> getOrdersInTimeRange(LocalDateTime fiveSecondsAgo, LocalDateTime currentTime) {
        return orderMapper.getOrdersInTimeRange(fiveSecondsAgo,currentTime);
    }

}
